package com.haoqizhe.kernel.commons.util;

import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

/**
 * ApplicationContext 上下文工具类
 *  以静态变量保存Spring ApplicationContext，方便使用
 * @author haoqizhe.li
 * @date 2018/5/10
 **/
@Component
public class SpringContextUtil implements ApplicationContextAware {

    private static ApplicationContext applicationContext;

    /**
     * 实现ApplicationContextAware接口 注入 context
     * @param applicationContext 上下文对象
     * @author haoqizhe.li
     * @date 2018/5/10 23:35
     */
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) {
        SpringContextUtil.applicationContext = applicationContext;
    }

    /**
     * 取得存储在静态变量中的ApplicationContext.
     * @author haoqizhe.li
     * @date 2018/5/10 23:35
     */
    public static ApplicationContext getApplicationContext() {
        checkApplicationContext();
        return applicationContext;
    }

    /**
     * 从静态变量ApplicationContext中取得Bean, 自动转型为所赋值对象的类型.
     * @author haoqizhe.li
     * @date 2018/5/10 23:35
     */
    @SuppressWarnings("unchecked")
    public static <T> T getBean(String name) {
        checkApplicationContext();
        return (T) applicationContext.getBean(name);
    }

    /**
     * 从静态变量ApplicationContext中取得Bean, 自动转型为所赋值对象的类型.
     * @author haoqizhe.li
     * @date 2018/5/10 23:35
     */
    @SuppressWarnings("unchecked")
    public static <T> T getBean(Class<T> clazz) {
        checkApplicationContext();
        return (T) applicationContext.getBean(clazz);
    }

    /**
     * 清除applicationContext静态变量.
     * @author haoqizhe.li
     * @date 2018/5/10 23:35
     */
    public static void cleanApplicationContext() {
        applicationContext = null;
    }

    /**
     * 校验 上下文是否存在
     * @author haoqizhe.li
     * @date 2018/5/10 23:35
     */
    private static void checkApplicationContext() {
        if (applicationContext == null) {
            throw new IllegalStateException("applicaitonContext未注入,请先注入SpringContextUtil bean");
        }
    }
}
